package com.boot.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class JwtTokenUtil {

    private static final String CLAIM_KEY_USERNAME = "sub";

    @Value("${jwt.token.secret}")
    private String secret;

    @Value("${jwt.token.expire}")
    private Long expire;

    public String generateToken(String str) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, str);
        return generateToken(claims);
    }

    private String generateToken(Map<String, Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    private Date generateExpirationDate(){
        return new Date(System.currentTimeMillis() + expire * 1000);
    }

    public String getUsernameFromToken(String token){
        String str;
        try{
            Claims claims = getClaimsFromToken(token);
            str = claims.getSubject();
        }catch (Exception e){
            str = null;
        }
        return str;
    }

    private Claims getClaimsFromToken(String token){
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            log.error("JWT格式验证失败:{}", token);
        }
        return claims;
    }
}
